<?php
namespace Home\Controller;
use Think\Controller;
use Server\PayService;
use Think\AjaxPage;
use Think\Page;
class UserController extends BaseController {
    public function __construct() {
        parent::__construct();
        $this->assign('act','user');
    }
    public function index(){
		$mod = M('users');
		$user_id = session('user_id');
		$info = $mod->where(array('id'=>$user_id))->field('id,user_name,head_picture')->find();
		$this->assign('info',$info);
        $this->display();
    }
    //我的订单
    public function order(){
        auatomatic();
		$this->check_order_status();
		$this->check_order_pay_status();
        $type = I('type_id')?I('type_id'):1;
        if(i('act')=='ajax') {
            $mod = M('orders');
            $goods_mod = M('orders_goods');
            $user_id = session('user_id');
            $where = array('a.user_id' => $user_id, 'a.is_child' => 0, 'a.is_delete' => 0);
            if($type==2){
                $where['a.status'] = 1;
            }else if($type==3){
                $where['a.status'] = 2;
                $where['a.order_status'] = 0;
            }else if($type==4){
                $where['a.status'] = 2;
                $where['a.order_status'] = 1;
            }else if($type==5){
                $where['a.status'] = 2;
                $where['a.order_status'] = 2;
                $where['a.is_comment'] = 0;
            }else if($type==6){
                $where['a.status'] = 2;
                $where['a.order_status'] = 2;
            }
            $count = $mod ->alias('as a')->where($where) ->count();
            $page_count = 20;
            $now_page = I('page') ? I('page') : 1;
            $Page = new AjaxPage($count, $page_count);
            $total_pages = ceil($count / $page_count);
            $is_page = 0;
            if ($now_page >= $total_pages) {
                $is_page = 1;
            }
            $order_list = $mod->alias('as a')
                ->where($where)->field('a.id,a.order_sn,a.status,a.order_status,a.is_comment')
                ->order('a.pay_time desc,a.add_time desc')
                ->limit($Page->firstRow . ',' . $Page->listRows)
                ->select();
            foreach ((array)$order_list as $k => $v) {	
                $order_list[$k]['goods_list'] = $goods_mod->alias('as a')
                    ->join('left join ' . C('DB_PREFIX') . 'goods as b on b.id=a.goods_id')
                    ->join('left join ' . C('DB_PREFIX') . 'business as d on d.id=a.store_id')
                    ->join('left join ' . C('DB_PREFIX') . 'goods_store_spec as c on c.id=a.spec_id')
                    ->where(array('a.order_sn' => $v['order_sn']))
                    ->field('a.goods_price,a.goods_id,a.goods_number,b.goods_name,b.thumb,c.spec_name,d.store_name,d.id as store_id')
                    ->select();
                foreach ((array)$order_list[$k]['goods_list'] as $kk => $vv) {
                    $order_list[$k]['goods_list'][$kk]['left_price'] = intval($vv['goods_price']);
                    $order_list[$k]['goods_list'][$kk]['right_price'] = substr($vv['goods_price'], -3, 3);
                }
            }
            exit(json_encode(array('is_page' =>$is_page,'code'=>200,'result'=>$order_list)));
        }
        $this->assign('status_name',status_name($type));
        $this->assign('type_id',$type);
        $this->display();
    }
    //立即支付
    function imme_order(){
        $user_id = session('user_id');
		if($user_id){
			$order_id = i('order_id')?i('order_id'):'';
			$pay_type = i('pay_type')?i('pay_type'):'';
			$order = M('orders')->where(array('user_id'=>$user_id,'id'=>$order_id))->field('id,order_sn,order_price,pro_price,cou_price')->find();
			if($pay_type=='微信支付'){
				$pay_result = PayService::openidPay($order['order_sn'],$order['order_price'],$order['order_price']+$order['cou_price']+$order['pro_price'],C('ORDER_URL'));
				if($pay_result['code'] === 0) {
					$token = $pay_result['data'];
				}
				exit(json_encode(array('code'=>200,'result'=>$token)));
			}
		}		
    }
	//余额支付
	function imme_order_yue(){
		$user_id = session('user_id');
		if($user_id){
			$mod = M('orders');
			$order_id = i('order_id')?i('order_id'):'';
			$pay_type = i('pay_type')?i('pay_type'):'';
			$order = $mod->where(array('user_id'=>$user_id,'id'=>$order_id))->field('id,order_sn,order_price,pro_price,cou_price')->find();
			$u_mod = M('users');
			if($pay_type=='余额支付'){
				$count_price = $order['order_price'];
				$md_pwd = md5(md5(i('pwd')).C('DB_DEVE'));
				$pwd = M('users_pwd')->where(array('user_id'=>$user_id,'password'=>$md_pwd ))->count();
				if(!$pwd){
					exit(json_encode(array('code' => 100,'msg' =>'密码错误')));
				}
				$user_price = $u_mod->where(array('id'=>$user_id))->getField('price');
				if($user_price<$count_price){
					exit(json_encode(array('code' => 100,'msg' => '余额不足，请及时充值。')));
				}
				$r = $u_mod->where(array('id'=>$user_id))->save(array('price'=>($user_price-$count_price)));
				if($r){
					$users_log_mod = M('users_log');
					$users_log_mod->add(array(
						'user_id'=>$user_id,
						'type_id'=>1,
						'price'=>$count_price,
						'integral'=>0,
						'add_time'=>time()
					));
					$this->order_log($order['order_sn'],'待发货','支付成功，商家拣货中');
					orders_status($user_name,$order['order_sn'],2,0,'');
					business_log($order['order_sn'],1);
					$mod->where(array('order_sn'=>$order['order_sn']))->save(array('status'=>2,'pay_time'=>time()));
					$this->success_pay_order($order['order_sn']);
					exit(json_encode(array('code'=>200,'result'=>'支付成功')));
				}
			}
		}		
	}
    //取消订单
    public function del_order(){
        $mod = M('orders');
        $order_id = I('order_id')?I('order_id'):'';
        $user_id = session('user_id');
        if($user_id){
            $result = $mod->where(array('id'=>$order_id))->save(array('status'=>4));
            if($result){
                exit(json_encode(array('code'=>200,'msg'=>'取消成功')));
            }else{
                exit(json_encode(array('code'=>100,'msg'=>'取消失败')));
            }
        }
    }
    //确认收货
    public function confirm_receipt(){
        $order_id = I('order_id')?I('order_id'):'';
        $user_id = session('user_id');
        if($user_id && $order_id){
            $mod = M('orders');
            $order_info = $mod->where(array('id'=>$order_id,'user_id'=>$user_id))->field('id,order_sn,status,order_status')->find();
            if(!$order_info['id']){
                exit(json_encode(array('code'=>100,'msg'=>'非法操作')));
            }
            if($order_info['order_status']==2){
                exit(json_encode(array('code'=>100,'msg'=>'您已确认了收货')));
            }
            if($order_info['status']!=2){
                exit(json_encode(array('code'=>100,'msg'=>'请先支付该订单')));
            }
            $result = $mod->where(array('id'=>$order_id))->save(array('order_status'=>2,'confirm_time'=>time()));
            if($result) {
				business_log($order_info['order_sn'],1);
                give_integral($order_info['order_sn']);//积分计算
                $user_name = M('users')->where(array('id'=>$user_id))->getField('user_name');
                orders_status($user_name, $order_info['order_sn'], 2, 2, '');
                order_log($order_info['order_sn'], '已完成', '订单已完成，赶快去评论吧！');
                exit(json_encode(array('code'=>200,'msg'=>'确认成功')));
            }
        }
    }
    //我的订单详情
    public function order_detail(){
        $mod = M('orders');
        $log_mod = M('orders_log');
        $goods_mod = M('orders_goods');
        $user_id = session('user_id');
        $order_id = I('order_id')?I('order_id'):'';
        if($order_id){
            $order_info = $mod->where(array('id'=>$order_id,'user_id'=>$user_id))->find();
            $order_info['goods_list'] = $goods_mod->alias('as a')
                ->join('left join '.C('DB_PREFIX').'goods as b on b.id=a.goods_id')
                ->join('left join '.C('DB_PREFIX').'business as d on d.id=a.store_id')
                ->join('left join '.C('DB_PREFIX').'goods_store_spec as c on c.id=a.spec_id')
                ->where(array('a.order_sn'=>$order_info['order_sn']))
                ->field('b.thumb,b.goods_name,d.store_name,c.spec_name,a.goods_price,a.goods_number')
                ->select();
            $order_info['status_list'] = $log_mod->where(array('order_sn'=>$order_info['order_sn']))->order('id desc')->select();
            $this->assign('info',$order_info);
            $this->display();
        }
    }
    //添加评论
    public function add_comment(){
        $mod = M('orders');
        $goods_mod = M('orders_goods');
        $user_id = session('user_id');
        $order_id = I('order_id')?I('order_id'):'';
        if($order_id && $user_id){
            if(IS_POST){
                if ($_FILES['file']['name']) {
                    $name = _uploadOne('file', '');
                    exit(json_encode(array('result' => $name)));
                }
                $data = I('post.');
                $info = $goods_mod->where(array('id'=>$data['order_id']))->field('order_sn,goods_id,store_id,spec_id')->find();
                $check = $mod->where(array('order_sn'=>$info['order_sn'],'is_comment'=>1))->count();
                if($check){
                    exit(json_encode(array('code'=>100,'msg'=>'已评论')));
                }
                $data['order_sn'] = $info['order_sn'];
                $data['spec_id'] = $info['spec_id'];
                $data['user_id'] = $user_id;
                $data['goods_id'] = $info['goods_id'];
                $data['store_id'] = $info['store_id'];
                $data['images'] = rtrim($data['images'],',');
                $data['add_time'] = time();
                $comment_mod = M('orders_comment');
                $result = $comment_mod->add($data);
                if($result){
                    $number = $goods_mod->where(array('order_sn'=>$info['order_sn']))->count();
                    $check_number = $goods_mod->where(array('order_sn'=>$info['order_sn'],'is_comment'=>1))->count();
                    if($number-1==$check_number){
                        $mod->where(array('order_sn'=>$data['order_sn']))->save(array('is_comment'=>1));
                    }
                    $goods_mod->where(array('id'=>$data['order_id']))->save(array('is_comment'=>1));
                    exit(json_encode(array('code'=>200,'msg'=>'评论成功')));
                }
            }else{
                $info = $mod->alias('as a')
                    ->join('left join '.C('DB_PREFIX').'orders_goods as b on b.order_sn=a.order_sn')
                    ->join('left join '.C('DB_PREFIX').'goods as c on c.id=b.goods_id')
                    ->where(array('a.id'=>$order_id))
                    ->field('c.goods_name,c.thumb,b.spec_id,b.id')
                    ->select();
                $this->assign('info',$info);
                $this->display();
            }
        }
    }
    //设置
    public function setting(){
        $this->display();
    }
    //我的优惠券
    public function coupon(){
        $mod = M('users_coupon');
        $type_id = I('type_id')?I('type_id'):'1';
        if(i('act')=='ajax'){
            $user_id = session('user_id');
            $where['a.user_id'] = $user_id;
            $time = time();
            if($type_id==1){
                $where['a.order_id'] = 0;
                $where['b.start_time'] = array('lt',$time);
                $where['b.end_time'] = array('gt',$time);
            }else if($type_id==2){
                $where['a.order_id'] = array('gt',0);
            }else if($type_id==3){
                $where['b.end_time'] = array('lt',$time);
            }
            $count = $mod ->alias('as a')
                ->join('left join '.C('DB_PREFIX').'goods_coupon as b on b.id=a.cou_id')
                ->where($where)
                ->count();
            $page_count = 20;
            $now_page = I('page') ? I('page') : 1;
            $Page = new AjaxPage($count, $page_count);
            $total_pages = ceil($count / $page_count);
            $is_page = 0;
            if ($now_page >= $total_pages) {
                $is_page = 1;
            }
            $coupon_list = $mod
                ->alias('as a')
                ->join('left join '.C('DB_PREFIX').'goods_coupon as b on b.id=a.cou_id')
                ->where($where)
                ->field("b.title,b.coupon_price,FROM_UNIXTIME(b.end_time,'%Y-%m-%d') as add_time")
                ->limit($Page->firstRow . ',' . $Page->listRows)
                ->select();
            exit(json_encode(array('is_page' =>$is_page, 'result' => $coupon_list)));
        }
        $this->assign('type_id',$type_id);
        $this->display();
    }
    //我的收藏
    public function collect(){
        $user_id = session('user_id');
        if($user_id){
            $this->display();
        }
    }
    //收藏列表
    function ajaxcollect(){
        $user_id = session('user_id');
        $mod = M('users_collect');
        $count = $mod->where(array('user_id'=>$user_id))->count();
        $Page = new AjaxPage($count, 10);
        $collect_list = $mod->alias('as a')
            ->join('left join '.C('DB_PREFIX').'business as c on c.id=a.store_id')
            ->join('left join '.C('DB_PREFIX').'goods as b on a.goods_id=b.id')
            ->field('a.id as cid,b.goods_name,b.thumb,b.shop_price,b.id,c.id as store_id,c.store_name')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $spec_mod = M('goods_store_spec');
        foreach((array)$collect_list as $k=>$v){
            $spec = $spec_mod->where(array('goods_id'=>$v['id'],'store_id'=>$v['store_id']))->order('spec_price asc')->find();
            $collect_list[$k]['spec_name'] = $spec['spec_name']?'规格：'.$spec['spec_name']:'';
            $collect_list[$k]['spec_id'] = $spec['id'] ?  $spec['id'] : '';
            if($spec['spec_price']){
                $collect_list[$k]['shop_price'] = $spec['spec_price'];
            }
            $collect_list[$k]['left_price'] = intval($collect_list[$k]['shop_price']);
            $collect_list[$k]['right_price'] = substr($collect_list[$k]['shop_price'],-3,3);
        }
        exit(json_encode(array('code'=>I('page'),'result'=>$collect_list)));
    }
    //取消收藏
    function cancle_collect(){
        $user_id = session('user_id');
        if($user_id) {
            $mod = M('users_collect');
            $id = I('cid') ? I('cid') : '';
            $mod->where(array('id'=>$id,'user_id'=>$user_id))->delete();
            exit(json_encode(array('code' => 200, 'msg' => '取消成功')));
        }
    }
    //关于我们
    public function about(){
        $this->display();
    }
    //新手帮助
    public function help(){
        $this->display();
    }
    //意见反馈
    public function feedback()
    {
        $user_id = session('user_id');
        if($user_id) {
            $mod = M('users_feedback');
            if (IS_POST) {
                if ($_FILES['file']['name']) {
                    $name = _uploadOne('file', '');
                    exit(json_encode(array('result' => $name)));
                }
                $data = i('post.');
                $data['user_id'] = $user_id;
                if($data['images']) {
                    $data['images'] = rtrim($data['images'],',');
                }
                $data['add_time'] = time();
                $data['add_ip'] = getIP();
                $result = $mod->add($data);
                if($result){
                    exit(json_encode(array('code'=>200,'msg'=>'反馈成功')));
                }else{
                    exit(json_encode(array('code'=>100,'msg'=>'反馈失败')));
                }
            }
            $this->display();
        }
    }
    //地址列表
    public function address(){
        $user_id = session('user_id');
        $mod = M('users_address');
        $address_list = $mod->where(array('user_id'=>$user_id))->select();
        $this->assign('address_list',$address_list);
        $this->display();
    }
    //操作地址
    public function add_address(){
        $act = I('act')?I('act'):'';
        $id = I('id')?I('id'):'';
        $data['user_id'] = session('user_id');
        $mod = M('users_address');
        if(IS_POST){
            $data['name'] = I('name')?I('name'):'';
            if(!$data['name']){
                exit(json_encode(array('code'=>100,'msg'=>'请输入收货人')));
            }
            $data['mobile'] = I('mobile')?I('mobile'):'';
            if(!$data['mobile']){
                exit(json_encode(array('code'=>100,'msg'=>'请输入电话号码')));
            }
            $data['address_area'] = I('area')?str_replace(',','',I('area')):'';
            $area_id = I('area_id')?I('area_id'):'';
            if($area_id){
               $a = explode(',',$area_id);
               $data['province'] = $a[0];
               $data['city'] = $a[1];
               $data['area'] = $a[2];
            }
            $data['address'] = I('address')?I('address'):'';
            if(!$data['address']){
                exit(json_encode(array('code'=>100,'msg'=>'请输入街道、楼牌号等')));
            }
            $url = 'http://restapi.amap.com/v3/geocode/geo?address='.str_replace(' ','',$data['address_area']).str_replace(' ','',$data['address']).'&output=JSON&key=f929e0f88a8b526632dcb6f887e49101';
            $content = json_decode(file_get_contents($url),true);
            $log = explode(',',$content['geocodes'][0]['location']);
            if($log[0]){
                $data['lng']=$log[0];
                $data['lat']=$log[1];
                $lng = M('config')->where(array('name'=>'lng'))->getField('value');
                $lat = M('config')->where(array('name'=>'lat'))->getField('value');
                $url = 'http://restapi.amap.com/v3/direction/driving?origin='.$lng.','.$lat.'&destination='.$log[0].','.$log[1].'&output=json&key=f929e0f88a8b526632dcb6f887e49101';
                $content = json_decode(file_get_contents($url),true);
                $data['infocode'] = $content['route']['paths'][0]['distance'];
            }
            if(I('act')=='add'){
                $mod->where(array('user_id'=>$user_id))->save(array('is_default'=>0));
                $data['is_default'] = 1;
                $data['add_time'] = time();
                $result = $mod->add($data);
                if($result){
                    exit(json_encode(array('code'=>200,'msg'=>'添加成功')));
                }else{
                    exit(json_encode(array('code'=>100,'msg'=>'添加失败')));
                }
            }else if(I('act')=='edit') {
                $data['up_time'] = time();
                $result = $mod->where(array('id'=>$id))->save($data);
                if($result){
                    exit(json_encode(array('code'=>200,'msg'=>'编辑成功')));
                }else{
                    exit(json_encode(array('code'=>100,'msg'=>'编辑失败')));
                }
            }
        }
        if($act=='edit' && $id){
            $info = $mod->where(array('id'=>$id))->find();
            $this->assign('info',$info);
        }
        $this->assign('act',$act);
        $this->display();
    }
    //设置默认地址
    public  function address_default(){
        $id = I('id')?I('id'):'';
        $user_id = session('user_id');
        $mod = M('users_address');
        if($user_id){
            $mod->where(array('user_id'=>$user_id))->save(array('is_default'=>0));
            $result = $mod->where(array('id'=>$id))->save(array('is_default'=>1));
            if($result){
                exit(json_encode(array('code'=>200,'msg'=>'设置成功')));
            }else{
                exit(json_encode(array('code'=>100,'msg'=>'设置失败')));
            }
        }else{
            exit(json_encode(array('code'=>100,'msg'=>'请登录')));
        }
    }
    //删除地址
    public function del_address(){
        $id = I('id')?I('id'):'';
        $user_id = session('user_id');
        $mod = M('users_address');
        if($user_id){
            $is_default = $mod->where(array('user_id'=>$user_id,'id'=>$id))->getField('is_default');
            if($is_default){
                $other_id = $mod->where(array('id'=>array('neq',$id),'user_id'=>$user_id))->getField('id');
                if($other_id){
                    $mod->where(array('id'=>$other_id))->save(array('is_default'=>1));
                }
            }
            $result = $mod->where(array('id'=>$id,'user_id'=>$user_id))->delete();
            if($result){
                exit(json_encode(array('code'=>200,'msg'=>'删除成功')));
            }else{
                exit(json_encode(array('code'=>100,'msg'=>'删除失败')));
            }
        }else{
            exit(json_encode(array('code'=>100,'msg'=>'请登录')));
        }
    }
    public function balance(){
		$this->balance_log();
        $user_id = session('user_id');
        $mod = M('users_log');
        $log_list = $mod->where(array('user_id'=>$user_id,'is_delete'=>0))->order('id desc')->select();
        $this->assign('log_list',$log_list);
        $user_mod = M('users');
        $user_info = $user_mod->where(array('id'=>$user_id))->field('give_integral,price')->find();
        $this->assign('user_info',$user_info);
        $this->display();
    }
	//判断充值是否有效
	public function balance_log(){
		$mod = M('users_log');
		$user_id = session('user_id');
        $log_list = $mod->where(array('user_id'=>$user_id,'type_id'=>2,'is_delete'=>0,'status'=>0))->order('id desc')->select();
		foreach((array)$log_list as $k=>$v){
			$pay_info = PayService::weChat_order_select($v['order_sn']);
			if($pay_info['data']['PaymentTime']){
				$this->success_pay_order($v['order_sn']);
			}else{
				$mod->where(array('id'=>$v['id']))->save(array('is_delete'=>1));
			}			
		}
	}
    //充值
    public function recharge(){
		if(i('act')=='ajax'){
			$price = I('price')?I('price'):'';
			$user_id = session('user_id');
			$mod = M('users_log');
			$order_sn = 'cz'.order_sn();
			$result = $mod->add(array(
				'order_sn'=>$order_sn,
				'user_id'=>$user_id,
				'price'=>$price,
				'type_id'=>2,
				'add_time'=>time()
			));
			if($result){
				$pay_result = PayService::openidPay($order_sn,$price,$price,C('BALANCE_URL'));
				if($pay_result['code'] === 0) {
					$token = $pay_result['data'];
				}
				exit(json_encode(array('code'=>200,'result'=>$token)));
			}
		}
        $this->display();
    }
    public function withdraw(){
        $this->display();
    }
    //支付密码设置与修改
    function pay_pwd(){
        $mod = M('users_pwd');
        $user_id = session('user_id');
        $pwd = I('pwd')?I('pwd'):'';
        if(isset($_POST['pwd'])){
            $id = I('id')?I('id'):'';
            if(!$pwd || strlen($pwd)<6){
                exit(json_encode(array('code'=>100,'msg'=>'请输入6位数字密码')));
            }
            $re_pwd = I('re_pwd')?I('re_pwd'):'';
            if($pwd!=$re_pwd){
                exit(json_encode(array('code'=>100,'msg'=>'两次输入的密码不一致')));
            }
            $data['password'] = md5(md5($pwd).C('DB_DEVE'));
            $data['user_id'] = $user_id;
            if(i('act')=='add') {
                $data['add_time'] = time();
                $result = $mod->add($data);
                if ($result) {
                    exit(json_encode(array('code' => 200, 'msg' => '设置成功')));
                }
            }else{
                $o_pwd = I('o_pwd')?I('o_pwd'):'';
                $old_pwd = $mod->where(array('id'=>$id))->getField('password');
                if($old_pwd!=md5(md5($o_pwd).C('DB_DEVE'))){
                    exit(json_encode(array('code'=>100,'msg'=>'原密码不正确')));
                }
                if($data['password']==$old_pwd){
                    exit(json_encode(array('code'=>100,'msg'=>'原密码与新密码不能相同')));
                }
                $data['up_time'] = time();
                $result = $mod->where(array('id'=>$id))->save($data);
                if ($result) {
                    exit(json_encode(array('code' => 200, 'msg' => '设置成功')));
                }
            }
        }
        $info = $mod->where(array('user_id'=>$user_id))->find();
        $this->assign('info',$info);
        $this->display();
    }
    //评论
    public function comment(){
        $user_id = session('user_id');
        if($user_id) {
            if(i('act')=='ajax') {
                $comment_mod = M('orders_comment');
                $comment_list = $comment_mod->alias('as a')
                    ->join(C('DB_PREFIX') . 'users as b on a.user_id=b.id')
                    ->where(array('a.user_id' => $user_id))
                    ->field('a.contents,b.head_picture,a.star,FROM_UNIXTIME(a.add_time,"%Y-%m-%d") as add_time,b.user_name,a.images')->select();
                foreach ((array)$comment_list as $k => $v) {
                    $v['images'] && $comment_list[$k]['images'] = explode(',', $v['images']);
                }
                exit(json_encode(array('code'=>200,'result'=>$comment_list)));
            }
            $this->display();
        }
    }
	
	function check_order_pay_status(){
		$user_id = session('user_id');
		$order_list = M('orders')->where(array('status'=>1,'user_id'=>$user_id))->field('order_sn')->group('order_sn')->select();
		foreach((array)$order_list as $k=>$v){
			$pay_info = PayService::weChat_order_select($v['order_sn']);
			if($pay_info['data']['PaymentTime']){
				$this->success_pay_order($v['order_sn']);
			}	
		}
	}
}